package com.self.audiocapture.move;

import android.graphics.PointF;
import android.util.Log;
import android.view.MotionEvent;

/**
 * @author huang
 */
public class MoveManager {
    private static final String TAG = "MoveManager";

    public static final int NO_CHECK = 0x01;
    public static final int CHECKING = 0x02;
    public static final int MOVING = 0x03;
    public static final int MOVE_END = 0x04;

    private IMoveControl moveControl;
    private PointF downPoint = new PointF();
    private static final int MAV_OFFSET = 20;

    public MoveManager(IMoveControl moveControl) {
        this.moveControl = moveControl;
        if(moveControl == null){
            throw new IllegalArgumentException("传入的 moveControl 不能为空");
        }
    }

    /**
     * @param event
     * @return 参考 {@link #NO_CHECK}, {@link #CHECKING}, {@link #MOVING}
     */
    public int updateData(MotionEvent event){
        // 这个是单指触控的事件获取
        // event.getAction()

        // 这个是多指触控的事件获取
        // event.getActionMasked()
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                if(moveControl != null){
                    moveControl.updateLastDownTime();
                    downPoint.set(event.getX(), event.getY());
                    return CHECKING;
                }
                break;

            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_HOVER_MOVE:
                if(moveControl != null){
                    if(moveControl.isLongTouch() && !moveControl.isMove()){
                        // 防止用户在判定时间间隔时，移动距离过大，导致闪过去的问题
                        if(Math.abs(downPoint.x - event.getX()) > MAV_OFFSET
                                || Math.abs(downPoint.y - event.getY()) > MAV_OFFSET){
                            return NO_CHECK;
                        }

                        Log.d(TAG, " moveControl.setMove1");
                        moveControl.setMove(true, event);
                        moveControl.move(moveControl, event);
                        return MOVING;

                    } else if(moveControl.isMove()) {
                        Log.d(TAG, " moveControl.setMove2");
                        moveControl.move(moveControl, event);
                        return MOVING;
                    }
                }
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                if(moveControl != null){
                    if(moveControl.isMove()){
                        moveControl.setMove(false, event);
                        return MOVE_END;
                    }
                }
                break;

            default:
        }

        return NO_CHECK;
    }
}
